package com.xq.service.impl;

import com.xq.entity.UmsUserRoles;
import com.xq.exception.BusinessException;
import com.xq.mapper.UmsUserRolesMapper;
import com.xq.service.IUmsRolesService;
import com.xq.service.IUmsUserRolesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xq.vo.DataBaseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuven
 * @since 2025-05-23
 */
@Service
public class UmsUserRolesServiceImpl extends ServiceImpl<UmsUserRolesMapper, UmsUserRoles> implements IUmsUserRolesService {

    @Autowired
    private UmsUserRolesMapper umsUserRolesMapper;

    @Autowired
    private IUmsRolesService umsRolesService;

    @Override
    public void insertUserRoles(String userId, String roleName) {
        String userRolesId = umsRolesService.getUserRolesId(roleName);
        UmsUserRoles umsUserRoles = new UmsUserRoles();
        umsUserRoles.setUserId(userId);
        umsUserRoles.setRoleId(roleName);
        int insert = umsUserRolesMapper.insert(umsUserRoles);
        if (insert < 0) {
            throw new BusinessException(DataBaseEnum.INSERTION_FAILED);
        }
    }

    @Override
    public List<String> listUserRoles(String userId) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("user_id", userId);
        List<UmsUserRoles> umsUserRoles = umsUserRolesMapper.selectByMap(map);
        if (umsUserRoles == null || umsUserRoles.size() == 0) {
            throw new BusinessException(DataBaseEnum.DATA_NOT_FOUND);
        }
        List<String> list = new ArrayList<String>();
        for (UmsUserRoles umsUserRole : umsUserRoles) {
            list.add(umsUserRole.getRoleId());
        }
        return list;
    }

    @Override
    public void deleteUserRoles(String userId, String roleName) {
        String userRolesId = umsRolesService.getUserRolesId(roleName);
        Map<String,Object> map=new HashMap<>();
        map.put("user_id", userId);
        map.put("role_id", userRolesId);
        int i = umsUserRolesMapper.deleteByMap(map);
        if (i < 0) {
            throw new BusinessException(DataBaseEnum.DELETE_FAILED);
        }
    }

}
